package com.share.tools;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * @author caifan
 * @date 2019/10/20
 */
public class URLConnectionUtils {

    public InputStream getInputstreamByUrl(String dataUrl, String fileName) throws Exception {
        URL url = new URL(dataUrl);
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");

        //设置请求属性
        urlConnection.setRequestProperty("Content-Type", "application/json;");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestProperty("Charset", "UTF-8");

        OutputStream outputStream = urlConnection.getOutputStream();
        StringBuffer params = new StringBuffer();
        params.append("enterpriseId=4000000");
        params.append("&&queueQids=40000000001");
        params.append("&&userName=admin");
        params.append("&&pwd=fccb085c3da4195e100604b4bb1fee98");
        params.append("&&seed=abc");
        outputStream.write(params.toString().getBytes());
        outputStream.flush();
        urlConnection.connect();
        System.out.println(urlConnection.getResponseCode());
        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = urlConnection.getInputStream();

            /**
             * 根据实际需求修改
             */
            GZIPInputStream gzip = new GZIPInputStream(is);
            String str = IOUtils.toString(gzip, "GBK");

            PrintWriter pw = new PrintWriter(fileName);
            pw.println(str);
            pw.flush();
            pw.close();
        }
        return urlConnection.getInputStream();
    }

    public InputStream httpPost(String url) throws Exception {
        HttpClient client = HttpClients.createDefault();

        HttpPost post = new HttpPost(url);
        HttpResponse httpResponse = client.execute(post);
        HttpEntity entity = httpResponse.getEntity();

        InputStream inputStream = entity.getContent();
        /**
         * 根据实际情况修改
         */
        GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
        String str = IOUtils.toString(gzipInputStream, "GBK");
        FileOutputStream fos = new FileOutputStream("D:/test20180724.txt.gz");
        IOUtils.copy(inputStream, fos);

        return inputStream;
    }

}
